package com.cqggrw.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.cqggrw.dao.LinkDaoI;
import com.cqggrw.domain.Link;
import com.cqggrw.util.DBUtil;
import com.cqggrw.util.Utils;

public class LinkDaoImpl implements LinkDaoI {

	public boolean add(Link link) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "insert into tbl_link(name, url) values(?, ?);";
		int i = 0;
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setString(1, link.getName());
			ps.setString(2, link.getUrl());
			i = ps.executeUpdate();
		} catch (Exception e) {
			Utils.log(e);
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1;
	}

	public boolean del(Integer id) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "delete from tbl_link where id = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			i = ps.executeUpdate();
		} catch (Exception e) {
			Utils.log(e);
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1;
	}

	public boolean modify(Link link) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "update tbl_link set name = ?, url = ? WHERE ID = ?;";
		int i = 0;
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setString(1, link.getName());
			ps.setString(2, link.getUrl());
			ps.setInt(3, link.getId());
			i = ps.executeUpdate();
		} catch (Exception e) {
			Utils.log(e);
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return i == 1;
	}

	public Link get(Link link) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "SELECT * FROM tbl_link where id = ?;";
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, link.getId());
			rs = ps.executeQuery();
			link = null;
			if (rs.next()) {
				link = new Link();
				link.setId(rs.getInt("id"));
				link.setName(rs.getString("name"));
				link.setUrl(rs.getString("url"));
			}
		} catch (Exception e) {
			Utils.log(e);
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return link;
	}

	public List<Link> get() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Link link = null;
		List<Link> list = new ArrayList<Link>();
		
		String sql = "SELECT * FROM tbl_link;";
		try {
			conn = DBUtil.getConn();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				link = new Link();
				link.setId(rs.getInt("id"));
				link.setName(rs.getString("name"));
				link.setUrl(rs.getString("url"));
				list.add(link);
			}
		} catch (Exception e) {
			Utils.log(e);
		} finally {
			DBUtil.close(conn, ps, rs);
		}
		return list;
	}

}
